from pymongo import MongoClient
import json
from bson import ObjectId

# 自定义JSON编码器，处理ObjectId
class MongoJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)  # 将ObjectId转换为字符串
        return super().default(o)

# 连接MongoDB
client = MongoClient("mongodb://localhost:27017")
db = client.page

# 可以自定义集合名
collection_name = "wxbebb3cdd9b331046"  # 替换为你的小程序集合名
data = list(db[collection_name].find())

# 输出到JSON文件
output_file = f"{collection_name}_export.json"
with open(output_file, "w", encoding="utf-8") as f:
    json.dump(data, f, cls=MongoJSONEncoder, ensure_ascii=False, indent=2)

print(f"已成功导出 {len(data)} 条记录到 {output_file}") 